package com.relife.sys.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.relife.common.model.AjaxJson;
import com.relife.common.model.Page;
import com.relife.common.utils.DateUtil;
import com.relife.common.utils.StringUtil;
import com.relife.core.entity.FileEntity;
import com.relife.sys.service.DeploymentService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


@Controller
@RequestMapping("sys/deployment")
public class DeploymentController extends BaseController {
	@Autowired
	private DeploymentService deploymentService;
	@Autowired
	protected RepositoryService repositoryService;

	/**
	 * 
	 * @author WU
	 * @date 2016年4月30日 下午11:29:12
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String deploymentList(HttpServletRequest req) {
		return "sys/deployment/deploymentList";
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年4月30日 下午11:29:17
	 * @param page
	 * @param res
	 */
	@RequestMapping
	public void listData(String name, Page page, HttpServletResponse res) {
		JSONObject row = new JSONObject();
		ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		if (StringUtil.isNotEmpty(name)) {
			query.processDefinitionNameLike("%" + name + "%");
		}

		List<ProcessDefinition> list = query.listPage(page.getStart(), page.getRows());
		JSONArray rows = new JSONArray();
		for (ProcessDefinition pd : list) {
			JSONObject obj = new JSONObject();
			Deployment deploy = repositoryService.createDeploymentQuery().deploymentId(pd.getDeploymentId()).singleResult();
			obj.put("id", pd.getId());
			obj.put("key", pd.getKey());
			obj.put("name", pd.getName());
			obj.put("deploymentId", pd.getDeploymentId());
			obj.put("suspended", pd.isSuspended());
			obj.put("version", pd.getVersion());
			obj.put("addTime", DateUtil.getTime(DateUtil.DATE_TIME, deploy.getDeploymentTime()));
			rows.add(obj);
		}
		row.put("total", query.count());
		row.put("rows", rows);
		this.write(row, res);
	}

	/**
	 * 查看流程文件
	 * 
	 * @author WU
	 * @date 2016年5月1日 下午12:22:17
	 * @param id
	 * @param type
	 * @param res
	 * @throws IOException
	 */
	@RequestMapping
	public void viewFlowFile(String id, String type, HttpServletResponse res) throws IOException {
		ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();

		String resourceName = "";
		if (type.equals("image")) {
			resourceName = pd.getDiagramResourceName();
		} else if (type.equals("xml")) {
			resourceName = pd.getResourceName();
		}
		InputStream resourceAsStream = repositoryService.getResourceAsStream(pd.getDeploymentId(), resourceName);
		if (type.equals("xml")) {
    		BufferedReader in = new BufferedReader(new InputStreamReader(resourceAsStream,"GBK"));
    	    StringBuffer buffer = new StringBuffer();
    	    String line = "";
    	    while ((line = in.readLine()) != null){
    	      buffer.append(line);
    	    }
    	    res.setContentType("text/html;charset=utf-8");   
    	    res.setCharacterEncoding("UTF-8"); 
    	    res.getWriter().print(buffer.toString().replace("<", "&lt;").replace(">", "&gt;"));
		}else{
            byte[] b = new byte[1024];
            int len = -1;

            while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
                res.getOutputStream().write(b, 0, len);
            }
		}
	}

	/**
	 * 流程部署页面
	 * 
	 * @author WU
	 * @date 2016年4月30日 下午10:39:36
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String deployment(HttpServletRequest req) {
		return "sys/deployment/deployment";
	}

	/**
	 * 流程部署
	 * 
	 * @author WU
	 * @date 2016年4月30日 下午11:03:05
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson zipDeployment(FileEntity file) {
		AjaxJson j = new AjaxJson();
		try {
			deploymentService.zipDeployment(file);
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 删除流程
	 * 
	 * @author WU
	 * @date 2016年5月2日 下午1:07:04
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson del(String id) {
		AjaxJson j = new AjaxJson();
		try {
			deploymentService.delDeployment(id);
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 流程选择列表
	 * 
	 * @author WU
	 * @date 2016年5月20日 上午10:42:56
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String selectDeployment(HttpServletRequest req) {
		return "sys/deployment/selectDeployment";
	}

}
